/**
 * 
 */
package com.tvshows.structure.reader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.tvshows.structure.bdd.BddQueries;
import com.tvshows.structure.beans.Properties;

/**
 * @author tMidy
 * <p>
 * Operations on Configuration Files
 * </p>
 */
public class FileOperations
{

    /**
     * The file to read
     */
    private File file;

    /**
     * The list of properties
     */
    private final List<String> properties;

    /**
     * The path of the property
     */
    private String propertyPath;

    /**
     * The logger of the class
     */
    private static final Logger LOGGER = Logger.getLogger( FileOperations.class );

    /**
     * true if properties has changed
     */
    private boolean propertiesHasChanged;

    /**
     * The {@link FileOperations} instance
     */
    private static FileOperations fileOperations;

    /**
     * Property file default name
     */
    private static final String PROPERTYFILE_NAME = "/tvshows.properties";

    /**
     * Constructor of the class
     */
    public FileOperations()
    {
        properties = new ArrayList<String>();
    }

    /**
     * Reads the configuration
     * 
     * @return list of properties
     */
    public List<String> readProperties()
    {
        LOGGER.info( "Lecture des propriétés " );
        try
        {
            // Accès au path des propriétés
            propertyPath = BddQueries.getBddQueries().getPropertyPath();

            if ( null == propertyPath )
            {
                return properties;
            }
            else
            {
                file = new File( propertyPath );
            }
            readPropertiesFile();
            propertiesHasChanged = false;
        }
        catch ( Exception e )
        {
            LOGGER.error( "Erreur de connection ", e );
        }
        return properties;
    }

    /**
     * Reads the properties from the buffer
     */
    private void readPropertiesFile()
    {
        properties.clear();
        try
        {
            /*
             * The file reader
             */
            FileReader fileReader = new FileReader( file );
            /*
             * The buffered reader
             */
            BufferedReader bufferedReader = new BufferedReader( fileReader );

            /*
             * The line to analyze
             */
            String line;
            while ( ( line = bufferedReader.readLine() ) != null )
            {
                if ( line.contains( "TORRENT_SOFT_PATH" ) && line.split( "=" ).length > 1 )
                {
                    properties.add( line.split( "=" )[1] );
                }
            }

            bufferedReader.close();
            fileReader.close();
        }
        catch ( FileNotFoundException e )
        {
            LOGGER.error( e );
        }
        catch ( IOException e )
        {
            LOGGER.error( e );
        }
    }

    /**
     * Parses the properties file given
     * 
     * @param path the file to parse
     */
    public List<String> parseProperties( String path )
    {
        file = new File( propertyPath );
        readPropertiesFile();

        return properties;
    }

    /**
     * Changes the configuration
     * 
     * @param changesList the list of changes
     */
    public void writeProperties( Properties changesList )
    {
        try
        {
            StringBuilder builder = new StringBuilder();

            if ( changesList.getSoftwarePath() != null && !"".equals( changesList.getSoftwarePath() ) )
            {
                builder.append( "_TORRENT_SOFT_PATH=" ).append( changesList.getSoftwarePath() ).append( "\n" );
            }
            /*
             * The file Writer
             */
            FileWriter fileWriter = new FileWriter( file );
            fileWriter.write( builder.toString() );
            fileWriter.close();
            propertiesHasChanged = true;

        }
        catch ( FileNotFoundException e )
        {
            LOGGER.error( e );
        }
        catch ( IOException e )
        {
            LOGGER.error( e );
        }
    }

    /**
     * @return the property file path
     */
    public String getPropertyPath()
    {
        if ( propertyPath != null )
        {
            return propertyPath;
        }
        return "";
    }

    /**
     * @param propertyPath the propertyPath to set
     */
    public void setPropertyPath( String propertyPath )
    {
        this.propertyPath = propertyPath;
    }

    /**
     * Changes the fileName
     * 
     * @param text the name of the file
     */
    public void changeFile( String text )
    {
        if ( text.isEmpty() )
        {
            file = new File( System.getProperty( "user.dir" ) + PROPERTYFILE_NAME );
        }
        else
        {
            file = new File( text );
        }
    }

    /**
     * @return the singleton {@link FileOperations}
     */
    public static FileOperations getInstance()
    {
        if ( fileOperations == null )
        {
            fileOperations = new FileOperations();
        }
        return fileOperations;
    }

    /**
     * @return the properties
     */
    public List<String> getProperties()
    {
        return properties;
    }

    /**
     * @return true if properties have changed
     */
    public boolean isPropertiesHasChanged()
    {
        return propertiesHasChanged;
    }
}
